<template>
	<div>
		<div class="searchBox">
			<input @confirm="getValue()" confirm-type="search" v-model="name" type="search" placeholder="请搜索" :focus="show" />
			<image @click="getValue()" src="/static/images/ic_search.png" />
			<span v-show="show" @click="back()">取消</span>
		</div>
	</div>
</template>

<script>
	export default {
		props: {
			show: {
				default: true
			},
			value: {
				default: ''
			},
			keyHistory: {
				default: 'searchHistory'
			}
		},
		data() {
			return {
				name: ''
			};
		},
		watch: {
			value(val) {
				this.name = val;
				this.value = val;
			}
		},
		created() {
			this.name = this.value;
		},
		methods: {
			getValue() {
				if (this.name.trim().length == 0) {
					wx.showToast({
						title: '请输入搜索内容',
						icon: 'none',
						duration: 2000
					});
				} else {
					this.addSearchHistory(this.name);
					this.$emit('search', this.name);
				}
			},
			addSearchHistory(word) {
				let searchHistory = uni.getStorageSync(this.keyHistory) || [];
				for (let i = 0; i < searchHistory.length; i++) {
					if (searchHistory[i] == word) {
						searchHistory.splice(i, 1);
						break;
					}
				}
				searchHistory.unshift(word);
				uni.setStorageSync(this.keyHistory, searchHistory);
			},
			back() {
				wx.navigateBack({
					delta: 1
				});
			}
		}
	};
</script>

<style lang="scss" scoped>
	.searchBox {
		display: flex;
		align-items: center;
		position: relative;
		padding: 24rpx 30rpx;

		image {
			position: absolute;
			left: 46rpx;
			width: 30rpx;
			height: 30rpx;
		}

		input {
			flex: 1;
			border-radius: 40rpx;
			padding-left: 56rpx;
			height: 60rpx;
			font-size: 28rpx;
			background: #ffffff;
			box-shadow: rgba(0, 0, 0, 0.05) 0px 0px 0px 1px;
		}

		span {
			font-size: 26rpx;
			color: #999999;
			padding-left: 20rpx;
		}
	}
</style>